package com.hfjava.practice02;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @version V1.0
 * @ProjectName:IntelliJ IDEA
 * @PackageName: com.hfjava
 * @ClassName: ParserScores
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date 2020/1/4 9:10
 * @Copyright 大牛版板所有
 */
public class ParserScores {
    private static final String RELATIVE_PATH = "chapter06/data/Scores.xml";
    private static Document doc = null;

    static {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(RELATIVE_PATH);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static List<Student> xmlToList(){
        List<Student> studentList = new ArrayList<>();
        NodeList stuNodeList = doc.getElementsByTagName("student");
        for (int i = 0; i < stuNodeList.getLength(); i++) {
            Student student = new Student();
            Element element = (Element)stuNodeList.item(i);
            String studentID = element.getAttribute("id");
            student.setId(studentID);
            NodeList childList = (stuNodeList.item(i)).getChildNodes();
            for (int j = 0; j <childList.getLength() ; j++) {
                Node child = childList.item(j);
                if (child.getNodeType() == Node.ELEMENT_NODE){
                    Element childElement = (Element)child;
                    if ("name".equals(child.getNodeName())){
                        String name = childElement.getTextContent();
                        student.setName(name);
                    }
                    else if ("course".equals(child.getNodeName())){
                        String course = childElement.getTextContent();
                        student.setCourse(course);
                    }else {
                        String scores = childElement.getTextContent();
                        student.setScores(scores);
                    }
                }
            }
            studentList.add(student);
        }
        return studentList;
    }

    public static void saveXml(Document doc,String path) throws Exception {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT,"yes");
        transformer.transform(new DOMSource(doc),new StreamResult(new BufferedWriter
                (new OutputStreamWriter(new FileOutputStream(path)))));

    }

    public static void delete()throws Exception{
        NodeList stuNodeList = doc.getElementsByTagName("student");
        for (int i = 0; i < stuNodeList.getLength(); i++) {
            Element studentEle = (Element)stuNodeList.item(i);
            String stu = studentEle.getAttribute("id");
            if ("1".equals(stu)){
                studentEle.getParentNode().removeChild(studentEle);
            }
        }
        saveXml(doc,RELATIVE_PATH);
    }

    public static void  modify()throws Exception{
        NodeList stuNodeList = doc.getElementsByTagName("student");
        for (int i = 0; i < stuNodeList.getLength(); i++) {
            Element studentEle = (Element)stuNodeList.item(i);
            String stu = studentEle.getAttribute("id");
            if ("2".equals(stu)){
                NodeList childList = studentEle.getChildNodes();
                for (int j = 0; j <childList.getLength() ; j++) {
                    Node child = childList.item(j);
                    if ("score".equals(child.getNodeName())) {
                        child.setTextContent("60");
                    }
                }
            }
        }
        saveXml(doc,RELATIVE_PATH);
    }

    public static void add()throws Exception{
        Element newID = doc.createElement("student");
        newID.setAttribute("id","5");
        Element newName = doc.createElement("name");
        newName.setTextContent("王浩");
        newID.appendChild(newName);
        Element newCourse = doc.createElement("course");
        newCourse.setTextContent("python");
        newID.appendChild(newCourse);
        Element newScore = doc.createElement("score");
        newScore.setTextContent("75");
        newID.appendChild(newScore);
        doc.getDocumentElement().appendChild(newID);
        saveXml(doc,RELATIVE_PATH);
    }

    public static void main(String[] args) throws Exception{
        delete();
        modify();
        add();
        List<Student> studentList = xmlToList();
        System.out.println("学生数量为："+studentList.size());
        for (Student stu:studentList) {
            System.out.println("学号："+stu.getId());
            System.out.println("\t姓名："+stu.getName());
            System.out.println("\t课程："+stu.getCourse());
            System.out.println("\t分数："+stu.getScores());
        }

    }
}
